package com.huikeportal.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.huikeportal.controller.common.Lang;
import com.huikeportal.model.Language;
import com.huikeportal.model.ReportGraphData;
import com.huikeportal.model.SiteAllInfo;
import com.huikeportal.model.SiteCommon;
import com.huikeportal.model.UserInfo;
import com.huikeportal.model.UserSiteHistory;
import com.huikeportal.model.WordBook;
import com.huikeportal.model.common.SqlParameter;
import com.huikeportal.service.FootfallGlobalService;
import com.huikeportal.service.LoginService;
import com.huikeportal.service.SelectSiteService;
import com.huikeportal.service.TodayIndexesService;

@Controller
@Scope("prototype")
public class PresidentPanelController {
	@Autowired
	private HttpSession session;

	@Autowired
	private LoginService loginService;
	
	@Autowired
	private TodayIndexesService todayIndexesService;
	
	@Autowired
	private FootfallGlobalService footfallGlobalService;

	@Autowired
	SelectSiteService selectSiteService;
	@RequestMapping("/PresidentPanel")
	public String totalTraffic(ModelMap model,String siteId) throws Exception {
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo=loginService.getUserInfo(userInfo);
		String userId=userInfo.getUserId();
		 //获取当前系统语言
        String sysLang = session.getAttribute("sysLang").toString();
        //查询当前页面id
        SqlParameter sql = new SqlParameter();
        sql.setSysLang(sysLang);
        sql.setString("PresidentPanel");
        Integer menuId = selectSiteService.getMenuId(sql);
        //获取用户权限按钮信息
        List<WordBook> buttonList = loginService.getUserButtonList(sysLang,
                userId, menuId);
        
      
        /**初始化全局分析的指标权限*/
        /**获取用户指标权限*/
        HashMap<String, String>  indexGroupInfo = footfallGlobalService.getIndexGroupInfo();
        model.addAttribute("indexGroupInfo",JSONObject.fromObject(indexGroupInfo));
        HashMap<String, String>  indexInfo = footfallGlobalService.getIndexInfo();
        model.addAttribute("indexInfo",JSONObject.fromObject(indexInfo));
        /**初始化全局分析的指标权限结束*/
        
        
        /**
         * 判断用户有权限进入获取该页面数据吗，如果没有集团权限则不能进入该页面
         */
        String siteType = FootfallConstant.GLOBAL_SITETYPE; //场所类型是100
        SiteAllInfo siteAllInfo = footfallGlobalService.selectSiteByUserId(userInfo,siteType);
        String siteID = "";
        if (siteAllInfo == null||(siteAllInfo.getSiteid() == null) ||"".equals(siteAllInfo.getSiteid())) {
            	String menuHtml = loginService.getMenuHtml(userInfo, "footfallGlobal");
    			model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
    			return "noPermission";	
        }
		String sessionId=userId+menuId;
		UserSiteHistory userSiteHistory=new UserSiteHistory();;
		if(session.getAttribute(sessionId)!=null){
			userSiteHistory=(UserSiteHistory) session.getAttribute(sessionId);
		}
		/**从seesion中取siteid,首先查找session找，然后是页面传过来，再是根据用户取*/
		if(siteId!=null&& !siteId.equals("")){
			siteID=siteId;
		}else{
			if(userSiteHistory.getSiteId()!=null&&!userSiteHistory.getSiteId().equals("")){
				siteID=userSiteHistory.getSiteId();
			}else {
					siteID=siteAllInfo.getSiteid();
			}
		}
		
		//如果记录的siteId已经变更了，则取默认用户权限下的siteId
		SiteCommon siteCommon = selectSiteService.querySiteInfo(siteID);
		if(siteCommon == null){
			siteID=siteAllInfo.getSiteid();
		}
		
		userSiteHistory.setSiteId(siteID);
		userSiteHistory.setUserId(userId);
		userSiteHistory.setMenuId(menuId);
//		footfallGlobalService.updateUserSiteHistory(userSiteHistory);//修改数据库记录
		session.setAttribute(sessionId, userSiteHistory);//如果没有将新得到的siteId存入session
		
		if(siteID!=null&& !siteID.equals("")){
			HashMap<String, Object> todayIndexes;
			
			List<String> indexListCurrent = new ArrayList<String>();
			indexListCurrent.add("0");//客流量
			indexListCurrent.add("3");//销售额
//			todayIndexes= todayIndexesService.getTodayIndexes(siteID,indexListCurrent);//废弃：修改为直接取该集团下面所有的场所汇总，不判定总裁账号有没有广场权限，
			todayIndexes = todayIndexesService.getTodayIndexes(siteID,userInfo.getUserId(),indexListCurrent);
			
			String siteNames=footfallGlobalService.getSiteNames(siteID);
			model.addAttribute("siteName", siteNames);
			model.addAttribute("siteId", siteID);
			model.addAttribute("datetime", footfallGlobalService.getDate());
			model.addAttribute("todayIndexes",todayIndexes);
		}
		Language lang = Lang.getInfo(sysLang);
		model.addAttribute("lang",lang);
		String menuHtml = loginService.getMenuHtml(userInfo, "PresidentPanel");
		model.addAttribute("menuHtml", menuHtml);// 左侧菜单html
		return "PresidentPanel";
	}
	
	/**前台获取图表数据  */
	@RequestMapping("/presidentGraphData")
	@ResponseBody
	public HashMap<String , Object> presidentGraphData(HttpServletRequest request,HttpServletResponse response) throws Exception {
		
		
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		String type= request.getParameter("type").toString();//获取type类型 1是"客流";2是 "销售额";3是 "提袋率";4是 "客单价";5是 "人效";6 "坪效";7 "集客力";其他 "平均滞留时间";
		String days= request.getParameter("span").toString();//获取时间及其类型
		String[] Strings =days.split("_");
		//日周月年
		String timeType_table=Strings[0];
		//类型1、2小时，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType=Strings[1];
		
		String siteId=request.getParameter("siteId");//获取几天的数据
		
		HashMap<String , Object> paraMapResult=new HashMap<String, Object>();
		
		//查询图表
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("timeType", timeType);
		paraMap.put("timeType_table", timeType_table);//日周月年表
		paraMap.put("type", type);
		paraMap.put("siteId", siteId);
		paraMap.put("userInfo", userInfo);
		List<ReportGraphData> list= footfallGlobalService.getGraphData(paraMap);
		List<String> siteType = footfallGlobalService.getSiteTypes(siteId);
		/** 获取siteId 的场所类型中文名称*/
		String siteTypeName = "";
		if(siteType!=null&&!"".equals(siteType)){
			String siteType1 = siteType.get(0);
			siteTypeName = footfallGlobalService.getSiteTypeName(Integer.parseInt(siteType1));
		}
		paraMapResult.put("siteTypeName", siteTypeName);
		
	
		
		//插入数据日期类型，日周年月
		paraMapResult.put("timeType_table",timeType_table);
		//插入折线数据
		paraMapResult.put("result", list);
		//表格数据
		List<ReportGraphData> tableList = new ArrayList<ReportGraphData>();
//		//加入数据
//		for(ReportGraphData reportGraphData :list){
//			tableList.add(reportGraphData);
//		}
//		//去重
//		tableList.removeAll(compareList);
//		//加入对比数据
//		for(ReportGraphData reportGraphData :compareList){
//			tableList.add(reportGraphData);
//		}
		//获取表格数据
//		paraMapResult.put("loadTable", loadTable);
//		String siteN=todayIndexesService.getSiteNameBySiteId(siteId);//场所中文名称
		String siteNames=footfallGlobalService.getSiteNames(siteId);//前台导航栏地址 广场-场所
		paraMapResult.put("siteN", siteNames);
		String sitename=footfallGlobalService.getSiteName(siteId);//siteId的中文名称
		paraMapResult.put("siteName", sitename);
		paraMapResult.put("stadubiao", list.get(0).getYear()+"-"+list.get(0).getMonth());
		paraMapResult.put("endtubiao", list.get(list.size()-1).getYear()+"-"+list.get(list.size()-1).getMonth());
		
		return paraMapResult;
	}
	
	/**前台获取排行榜数据  */
	@RequestMapping("/getPresidentRanking")	
	@ResponseBody
	public HashMap<String , Object> getPresidentRanking(HttpServletRequest request,HttpServletResponse response) throws Exception {
		//场所
		String siteId= request.getParameter("siteId");
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo = loginService.getUserInfo(userInfo);//得到用户信息
		int type= Integer.parseInt(request.getParameter("type"));
		
		String timeType_table = "day";//天排行
		//类型，7、14、30天；4、8、12周；3、6、12月；3、5年
		String timeType = "1_2";//昨天一天
		
		String orderBy= request.getParameter("orderBy").toString();
		
		HashMap<String , Object> paraMap=new HashMap<String, Object>();
		paraMap.put("siteId", siteId);
		paraMap.put("type", type);
		paraMap.put("timeType_table", timeType_table);
		paraMap.put("timeType", timeType);
		paraMap.put("orderBy", orderBy);
		paraMap.put("userInfo", userInfo);
		List<HashMap<String,Object>> stringRank=footfallGlobalService.getRanking(paraMap);
		
		paraMap.put("result", stringRank);
		return paraMap;
	}
	
	
}
